package com.dstz.demo.rest.controller;


import com.alibaba.fastjson.JSONObject;
import com.dstz.base.api.response.impl.ResultMsg;
import com.dstz.bpm.api.engine.action.cmd.FlowRequestParam;
import com.dstz.bpm.engine.action.cmd.DefualtTaskActionCmd;
import com.dstz.bpm.rest.controller.BpmTaskController;
import com.dstz.demo.core.manager.AClClbManager;
import com.dstz.demo.core.manager.ClcsbManager;
import com.dstz.demo.core.manager.MatecodeManager;
import com.dstz.demo.core.manager.ServiceManager;
import com.dstz.demo.core.model.AClClb;
import com.dstz.demo.core.model.Clcsb;
import com.dstz.demo.core.model.Matecode;
import com.dstz.demo.core.model.Service;
import io.swagger.annotations.Api;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

@RestController
@RequestMapping({"/bpm/task/ppcg"})
@Api(
        description = "流程任务相关服务接口"
)
public class BpmTaskPPCGController extends BpmTaskController {

    @Resource
    MatecodeManager matecodeManager;

    @Resource
    ServiceManager serviceManager;


    @Resource
    AClClbManager aClClbManager;

    @Resource
    ClcsbManager clcsbManager;

    @PostMapping("/doCailiao")
    public ResultMsg<String> doAction(@RequestBody FlowRequestParam flowParam, HttpServletRequest request) throws Exception {
        String jsontablename="";
        if(flowParam.getTaskId()==null){
           return  super.doAction(flowParam);
        }else {
            DefualtTaskActionCmd taskModel = new DefualtTaskActionCmd(flowParam);
            String actionName = taskModel.executeCmd();

            JSONObject json = taskModel.getBusData();
            String value = "";
            for (Map.Entry<String, Object> entry : json.entrySet()) {
                System.out.println(entry.getKey() + ":" + entry.getValue());
//            value=entry.getValue().toString();
                jsontablename = entry.getKey();
                break;
            }
            if (!jsontablename.equals("a_cl_cllr2") && !jsontablename.equals("a_service")){
                return this.getSuccessResult(String.format("执行%s操作成功", actionName));
            }else {
                getBusData(json);
            }
            return this.getSuccessResult(String.format("执行%s操作成功", actionName));
        }
    }


    /**
     * 业务逻辑处理
     * @param json
     * @return
     */
    public void getBusData(JSONObject json){
        if(json!=null){
            for (Map.Entry<String, Object> entry : json.entrySet()) {
                String key=entry.getKey();
                if(key.equals("a_cl_cllr2")){//添加物料信息逻辑
                    JSONObject busdata=(JSONObject)json.get("a_cl_cllr2");
                    if(busdata.get("zt").equals("dsh")){
                        String id=busdata.get("id").toString();//id
                        String matecode=busdata.get("wlbm").toString();//物料编码
                        String cpmc=busdata.get("cpmc").toString();//产品名称
                        updateMateCode(id,matecode,cpmc);
                    }
                }
                if(key.equals("a_service")){
                    JSONObject busdata=(JSONObject)json.get("a_service");
                    if(busdata.get("examinetatus").equals("dsh")){
                        String id=busdata.get("serviceid").toString();//id
                        String matecode=busdata.get("material_coding").toString();//物料编码
                        String cpmc=busdata.get("servicename").toString();//产品名称
                        updateMateCodes(id,matecode,cpmc);
                    }
                }
            }
        }
    }


    /**
     * 统计字符串中出现多少个字符
     * @param str
     * @return
     */
    public  static int countStr(String str){
        int flag=0;
            for(int x=0;x<str.length();x++){
                char ch = str.charAt(x);
                if(ch=='.'){
                    flag++;
                }
            }
        return flag+1;
    }

    public  String changeStr(int str){
        String strflag=str+"";
        String flag="";
        if(strflag.length()==1){
            flag="0"+strflag;
        }else{
            flag=strflag;
        }
        return flag;
    }


    public static void main2(String[] args){
        List<String> a=new ArrayList<>();
        a.add("01.01.01.01");
        a.add("01.01.01.03");
        a.add("01.01.01.02");
        a.add("01.01.01.04");
        a.add("01.01.01.05");



        Collections.reverse(a);

        String countstr=a.get(0);


        System.out.println(countStr(countstr)+"");


        System.out.println(a.get(0).substring(0,a.get(0).lastIndexOf(".")+1));

        for(int i=0;i<a.size();i++){
            System.out.println(a.get(i));
        }

    }


    /**
     * 修改物料编码编号
     * @param matecode
     * @param cpmc
     */
    public void updateMateCode(String id,String matecode,String cpmc) {
        String newmatecode="";
        Map mapparams=new HashMap();
        mapparams.put("whereSql","  pkey ='"+matecode+"'");

        Matecode matecodeDO = new Matecode();
        int level=countStr(matecode);
        matecodeDO.setCname(cpmc);
        matecodeDO.setPkey(matecode);
        matecodeDO.setClevel(level + 1);
        List<Matecode> ckeylist = matecodeManager.queryByCode(mapparams);
        if(ckeylist==null || ckeylist.size() < 1){//如果子类没有  后面累加01
            newmatecode=matecode+".01";
            matecodeDO.setCkey(newmatecode);

        }else{//如果子类有

            List<String> anum=new ArrayList<>();

            if(null != ckeylist && ckeylist.size() >0){
                for(int i=0;i<ckeylist.size();i++){
                    anum.add(ckeylist.get(i).getCkey());
                }
                Collections.reverse(anum);
                String max_num=anum.get(0);
                String max_numstr=max_num.substring(max_num.lastIndexOf(".")+1);
                String start_numstr=max_num.substring(0,max_num.lastIndexOf(".")+1);
                newmatecode=start_numstr+""+changeStr(Integer.parseInt(max_numstr)+1);
                matecodeDO.setCkey(newmatecode);
            }
        }

        matecodeManager.save(matecodeDO);
        AClClb aclclb = new AClClb();
        aclclb.setId(id);
        aclclb.setWlbm(newmatecode);
        aClClbManager.updateState(aclclb);
        Clcsb clcsb=new Clcsb();
        clcsb.setMaterialid(id);
        clcsb.setMaterielcodeid(newmatecode);
        clcsbManager.updates(clcsb);
    }

    public void updateMateCodes(String id,String matecode,String cpmc) {
        String newmatecode="";
        Map mapparams=new HashMap();
        mapparams.put("whereSql","  pkey ='"+matecode+"'");

        Matecode matecodeDO = new Matecode();
        int level=countStr(matecode);
        matecodeDO.setCname(cpmc);
        matecodeDO.setPkey(matecode);
        matecodeDO.setClevel(level + 1);
        List<Matecode> ckeylist = matecodeManager.queryByCode(mapparams);
        if(ckeylist==null || ckeylist.size() < 1){//如果子类没有  后面累加01
            newmatecode=matecode+".01";
            matecodeDO.setCkey(newmatecode);

        }else{//如果子类有

            List<String> anum=new ArrayList<>();

            if(null != ckeylist && ckeylist.size() >0){
                for(int i=0;i<ckeylist.size();i++){
                    anum.add(ckeylist.get(i).getCkey());
                }
                Collections.reverse(anum);
                String max_num=anum.get(0);
                String max_numstr=max_num.substring(max_num.lastIndexOf(".")+1);
                String start_numstr=max_num.substring(0,max_num.lastIndexOf(".")+1);
                newmatecode=start_numstr+""+changeStr(Integer.parseInt(max_numstr)+1);
                matecodeDO.setCkey(newmatecode);
            }
        }

        matecodeManager.save(matecodeDO);
        Service service=new Service();
        service.setServiceid(id);
        service.setMaterial_coding(newmatecode);
        serviceManager.updates(service);
    }



}
